<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="设备唯一id" prop="deviceId">
        <el-input v-model="queryParams.deviceId" placeholder="请输入设备唯一id" clearable />
      </el-form-item>
      <el-form-item label="设备名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入设备名称" clearable />
      </el-form-item>
      <el-form-item label="项目id" prop="name">
        <el-select clearable="" v-model="queryParams.projectId" filterable placeholder="请选择项目">
          <el-option v-for="item in project_list" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <!-- <el-input v-model="queryParams.projectId" placeholder="请输入设备id" clearable /> -->
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="queryParams.remark" placeholder="请输入备注" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['produce:produce-plan:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['produce:produce-plan:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
          @click="handleDelete">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['produce:produce-plan:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleBatch"
          v-hasPermi="['produce:produce-plan:add']">批量新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getMainDeviceList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="mainDevicelList" @selection-change="handleSelectionChange" >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备唯一id" align="center" prop="deviceId" :show-overflow-tooltip="true" />
      <el-table-column label="在线状态" prop="status" align="center" :render-header="renderHeader">
        <template slot-scope="scope">
          <div>
            <i :class="['status-icon', getColorMap(scope.row.status)]"></i>
            {{ scope.row.status === 1 ? '在线' : '离线' }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="设备名称" align="center" prop="name" :show-overflow-tooltip="true" />
      <el-table-column label="项目" align="center" prop="projectName" :show-overflow-tooltip="true" />

      <el-table-column label="设备组合" align="center" prop="deviceComposeName" :show-overflow-tooltip="true" />
      <el-table-column label="柜子类型" align="center" prop="containerTypeName" :show-overflow-tooltip="true" />
      <el-table-column label="生命周期" align="center" prop="factoryStatus" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.factory_status" :value="scope.row.factoryStatus"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="用户" align="center" prop="nickName" :show-overflow-tooltip="true" />
      <el-table-column label="位置" align="center" prop="address" :show-overflow-tooltip="true" />
      <el-table-column label="最后上线时间" align="center" prop="lastOnlineTime" :show-overflow-tooltip="true" />
      <el-table-column label="最后离线时间" align="center" prop="lastOddlineTime" :show-overflow-tooltip="true" />
      <!-- <el-table-column label="创建时间" align="center" prop="createTime" :show-overflow-tooltip="true" >
        <template slot-scope="scope">
          {{ parseTime(new Date(scope.row.createTime)) }}
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-sunny" @click="registryIot(scope.row)" v-show="scope.row.isRegistryIot === 0">注册至IOT平台</el-button>
          <el-button size="mini" type="text" icon="el-icon-circle-close" @click="Undeploy(scope.row)" v-show="scope.row.isDeploy === 1 && scope.row.isRegistryIot === 1">设备禁用</el-button>
          <el-button size="mini" type="text" icon="el-icon-circle-check" @click="Deploy(scope.row)" v-show="scope.row.isDeploy === 0 && scope.row.isRegistryIot === 1">设备激活</el-button>
          <el-button size="mini" type="text" icon="el-icon-search" @click="toShell(scope.row)">查看shell</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          <!-- <el-button size="mini" type="text" icon="el-icon-search" @click="toSls(scope.row)">查看日志</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getMainDeviceList" />

    <!-- 添加或修改设备对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目" prop="projectId">
              <el-select v-model="form.projectId" placeholder="请选择项目" clearable style="width:240px"
                @change="chooseProject()">
                <el-option v-for="item in project_list" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>

          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入设备名称" maxlength="25" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="型号组合" prop="composeId">
              <el-select v-model="form.composeId" placeholder="请选择型号组合" clearable style="width:240px"
                @change="itemChoose">
                <el-option v-for="item in project_model_compose_list_chose" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="柜子类型" prop="containerTypeId">
              <el-select v-model="form.containerTypeId" placeholder="请选择柜子类型" clearable style="width:240px"
                @change="itemChoose">
                <el-option v-for="item in project_container_type_list_chose" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="唯一标识类型" prop="soleType">
              <el-select v-model="form.soleType" placeholder="请选择类型" clearable style="width:240px"
                @change="chooseSoleType">
                <el-option v-for="item in sole_type_list" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="cpuId" prop="cpuId">
              <el-input v-model="form.cpuId" placeholder="请输入cpuId" maxlength="25" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="imeiCode" prop="imeiCode">
              <el-input v-model="form.imeiCode" placeholder="请输入imeiCode" maxlength="25" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="snCode" prop="snCode">
              <el-input v-model="form.snCode" placeholder="请输入snCode" maxlength="25" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>





        <el-row>
          <el-col :span="12">
            <el-form-item label="部门" prop="belongDept">
              <treeselect v-model="form.belongDept" :options="department_list" :normalizer="normalizer"
                placeholder="选择部门" style="width:217px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户" prop="belongUser">
              <el-select v-model="form.belongUser" placeholder="请选择" clearable style="width:240px" @change="itemChoose">
                <el-option v-for="item in user_list" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" placeholder="请输入" maxlength="40" show-word-limit />
          </el-form-item>
        </el-col>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>

    </el-dialog>
    <!-- 批量导入 -->
    <el-dialog :title="batchTitle" :visible.sync="batchOpen" width="700px" append-to-body>

      <el-form ref="batchform" :model="batchform" :rules="batchrules" label-width="140px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目" prop="projectId">
              <el-select v-model="batchform.projectId" placeholder="请选择项目" clearable 
                @change="chooseProject()">
                <el-option v-for="item in project_list" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>

          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="型号组合" prop="composeId">
              <el-select v-model="batchform.composeId" placeholder="请选择型号组合" clearable 
                @change="itemChoose">
                <el-option v-for="item in project_model_compose_list" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="柜子类型" prop="containerTypeId">
              <el-select v-model="batchform.containerTypeId" placeholder="请选择柜子类型" clearable 
                @change="itemChoose">
                <el-option v-for="item in project_container_type_list" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="唯一标识类型" prop="soleType">
              <el-select v-model="batchform.soleType" placeholder="请选择类型" clearable >
                <el-option v-for="item in sole_type_list" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="部门" prop="belongDept" >
              <treeselect v-model="batchform.belongDept" :options="department_list" :normalizer="normalizer"
                placeholder="选择部门" style="width:217px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户" prop="belongUser">
              <el-select v-model="batchform.belongUser" placeholder="请选择" clearable @change="itemChoose">
                <el-option v-for="item in user_list" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
          <ExportExcel :list="exportList" :tHeader="oHeader" :tValue="oValue" filename="导入模板下载">模板下载</ExportExcel>
      <div style="text-align: center;">
        <el-upload
        class="upload-demo"
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          action = "/"
          :on-change="handUploadExcel"
          :show-file-list="true"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :auto-upload="false"
          drag  
        >

          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitFileForm">开始导入</el-button>

      </div>
    </el-dialog>
  </div>
</template>

<script>

import { listMainDevice, getMainDeviceDetail, addMainDevice, updateMainDevice, exportMainDevice, delMainDevice, deployMainDevice, unDeployMainDevice,  registryIot,batchInsert } from "@/api/device/mainDevice";
import { listProject, getProjectDetail } from "@/api/project/project";
import { listContainerType } from "@/api/container/containerType";
import { listDeviceModelCompose } from "@/api/device/deviceModelCompose";
import { listUser, getUserInfoByUserId } from "@/api/system/user";
import { listDept } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getToken } from '@/utils/auth'
import { getUserProfile } from '@/api/system/user'
import ExportExcel from '../../../components/ExcelUtils/Export2Excel.vue'
import * as XLSX from 'xlsx'

const searchItem = [
  { label: '在线', value: 'ONLINE' },
  { label: '离线', value: 'OFFLINE' },
  { label: '未激活', value: 'UNACTIVE' },
  { label: '禁用', value: 'DISABLE' },
]

export default {
  name: "mainDevice",
  dicts: ['factory_status'],
  components: { Treeselect,ExportExcel },
  data() {
    return {
      //选中行数据的userid
      userId: '',
      userProfileId: '',//登录的用户id
      websocketData: '',
      // 表单数据
      form: {
        imeiCode: '',
        cpuId: '',
        snCode: '',
        departmentId: ''
      },
      //批量表单
      batchform: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中项目名数组
      token: getToken(),
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 主设备表格数据
      mainDevicelList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //批量新增弹窗
      batchOpen:false,
      //批量新增标题
      batchTitle:"",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn:'id',
        isAsc:'desc'
      },
      //上传的文件
      excelFileData:'',
      // 导出数据集合
      exportList: [{"name":"test","cpuId":"988","imeiCode":"345","snCode":"456",}],
      // 导出样例的抬头和数据
      oHeader: ['设备名称','cpuid',	'imeiCode',	'snCode'],
      oValue:['name','cpuId','imeiCode','snCode'], 
      //批量导入上传
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData"
      },
      // 产品列表
      product_list: [],
      // 用户列表
      user_list: [],
      // 柜子类型有
      project_container_type_list: [],
      // 型号组合有
      project_model_compose_list: [],

      // 绑定项目柜子类型有
      project_container_type_list_chose: [],
      // 绑定项目型号组合有
      project_model_compose_list_chose: [],

      // 项目列表
      project_list: [],
      // 部门列表
      department_list: [],
      // 是否注册iot平台
      isRegistryIot_list: [
        { label: '未注册', value: 0 },
        { label: '已注册', value: 1 },
      ],
      // 是否激活
      isDeploy_list: [
        { label: '未激活', value: 0 },
        { label: '已激活', value: 1 },
      ],
      // 唯一标识类型
      sole_type_list: [
        { label: 'cpu_id', value: '1' },
        { label: 'imei', value: '2' },
        { label: 'sn', value: '3' },
      ],

      // 表单校验
      rules: {
        projectId: [
          { required: true, message: "请先选择项目", trigger: "blur" }
        ],
        name: [
          { required: true, message: "设备名称不能为空", trigger: "blur" }
        ],
        composeId: [
          { required: true, message: "型号组合不能为空", trigger: "blur" }
        ],
        containerTypeId: [
          { required: true, message: "冰柜类型不能为空", trigger: "blur" }
        ],
        soleType: [
          { required: true, message: "唯一标识类型不能为空", trigger: "blur" }
        ],
        cpuId: [
          { required: false, message: "cpuId不能为空", trigger: "blur" }
        ],
        imeiCode: [
          { required: false, message: "imeiCode不能为空", trigger: "blur" }
        ],
        snCode: [
          { required: false, message: "snCode不能为空", trigger: "blur" }
        ],
      },
      //批量新增规则
      batchrules: {
        projectId: [
          { required: true, message: "请先选择项目", trigger: "blur" }
        ],
        composeId: [
          { required: true, message: "型号组合不能为空", trigger: "blur" }
        ],
        containerTypeId: [
          { required: true, message: "冰柜类型不能为空", trigger: "blur" }
        ],
        soleType: [
          { required: true, message: "唯一标识类型不能为空", trigger: "blur" }
        ],
      }
    };
  },
  watch: {
    'form.belongDept': {
      handler(val) {
        if (val) {
          this.chooseDepartment()
        }
      },
    },
    'batchform.belongDept': {
      handler(val) {
        if (val) {
          this.chooseDepartment()
        }
      },
    }
  },
  created() {
    // if (this.$route.query.projectId) {
    //   this.queryParams.projectId = this.$route.query.projectId
    // }
    this.getMainDeviceList();
    this.getProjectList();
    this.getContainerTypeList();
    this.getDeviceModelComposeList();
    this.getDeptList();
    this.getUserInfo()
  },
  methods: {
    // 跳转至shell详情页面
    toShell(row){
      this.$router.push({
        path: "/genius/platform-device/shellDetail/index/" + row.deviceId,
      });
    },
    // 激活设备
    Deploy(row){
      row.deviceIds = []
      row.projectIds = []
      row.deviceIds.push(row.deviceId)
      row.projectIds.push(row.projectId)
      deployMainDevice(row).then((res) =>{
        if(res.code === 200){
          this.$message({
            type: 'success',
            message: '启用成功'
          });
          this.getMainDeviceList();
        }
      })
    },
    // 禁用
    Undeploy(row){
      row.deviceIds = []
      row.projectIds = []
      row.deviceIds.push(row.deviceId)
      row.projectIds.push(row.projectId)
      unDeployMainDevice(row).then((res) =>{
        if(res.code === 200){
          this.$message({
            type: 'success',
            message: '禁用成功'
          });
          this.getMainDeviceList();
        }
      })
    },
    // 注册至IOT平台
    registryIot(row){
      row.deviceIds = []
      row.projectIds = []
      row.deviceIds.push(row.deviceId)
      row.projectIds.push(row.projectId)
      registryIot(row).then(response => {
        if(response.code === 200){
          this.$message({
            message: '设备注册成功！',
            type: 'success',
            duration: 1000
          });
          this.getMainDeviceList();
        }
      })
    },
    getUserInfo() {
      getUserProfile().then(response => {
        this.userProfileId = response.data.userId
      })
    },
    /** 多选框点击事件 */
    itemChoose() {
      // 用于解决值更新了表单不更新的问题
      this.$forceUpdate();
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    getColorMap(value) {
      // 在线 绿色   不在线红色  未激活黄色
      // emumStatus.ONLINE
      // emumStatus.OFFLINE
      // emumStatus.UNACTIVE

      let color = 'c-grey'
      switch (value) {
        case 1:
          color = 'c-green'
          break
        case 0:
          color = 'c-red'
          break
        default:
          break
      }
      return color
    },
    renderHeader(h, { column, $index }) {
      // h即为cerateElement的简写，具体可看vue官方文档
      return h('div', [
        h('span', column.label),
        h(
          'i',
          {
            class: 'el-icon-filter',
            style: 'color:#409eff;pointer-events: auto;',
            on: {
              click: () => {
                //一定要用箭头函数
                this.switchClick($index, column)
              },
            },
          },
          ''
        ),
      ])
    },
    /**
     * WebSocket
     */
    initSocket: function () {
      // if(typeof(WebSocket) === "undefined"){
      //           alert("您的浏览器不支持socket")
      //       }else{

      // 实例化socket
      //`${this.$wsapi}/smart/wx/${testUserID}/${deviceId}`
      // wss://api-smart.mvtlabs.com
      this.WebSocket = new WebSocket(`${this.$wsapi}/genius/webSocket/${this.userProfileId}` + `?Authorization=Bearer ` + getToken());
      console.log('this.WebSocket', this.WebSocket)
      // 监听socket连接
      this.WebSocket.onopen = this.openSocket
      // 监听socket错误信息
      this.WebSocket.onerror = this.error
      // 监听socket消息
      this.WebSocket.onmessage = this.getMessage

      // }
    },
    openSocket: function () {
      console.log("socket连接成功")
    },
    error: function () {
      console.log("连接错误")
    },
    getMessage: function (e) {
      console.log(e)
      // this.websocketData = JSON.parse(e.data)
      // console.log('this.websocketData', this.websocketData);
      // let deviceList = Array.from(this.websocketData)
      // let list = Array.from(this.mainDevicelList)
      //  list.map((item2) => {
      //   deviceList.map((item1) => {
      //     if (item2.id == item1.id) {
      //       console.log('成功');
      //       item2.status = item1.status
      //     }
      //   })
      // })
      // return list


    },
    send: function () {
      //参数写这里
      this.socket.send('126')
    },
    close: function () {
      console.log("socket已经关闭")
    },
    /** 选择部门 */
    chooseDepartment() {
      //先清空
      this.form.belongUser = null
      this.user_list = []
      const params = {
        deptId: parseInt(this.form.belongDept)
      }
      if(this.batchOpen == true){
        params.deptId = parseInt(this.batchform.belongDept)
      }
      listUser(params).then((res) => {
        if (res.code === 200 && res.data) {
          for (var i = 0; i < res.data.records.length; i++) {
            let temp = {
              value: res.data.records[i].userId.toString(),
              label: res.data.records[i].nickName
            }
            this.user_list.push(temp)
          }
        }
      })
      if (this.userId) {
        this.form.belongUser = this.userId
        this.userId = ''
      }
    },
    /**下载模板 */
    importTemplate(){
      this.download('system/user/importTemplate', {
      }, `user_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    handUploadExcel(file,fileList){
      // 校验文件
      if (!file) {
        this.$confirm("读取excel文件数据失败，请尝试重新上传文件！", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        })
        // 如果没有文件 - 当然也可以提醒用户弹个警告框 但是基本没有这种情况的出现
        return false;
      }else if (!/\.(xls|xlsx)$/.test(file.name.toLowerCase())) {
        // 文件格式的判断
        this.$message.error("上传格式不正确，请上传xls或者xlsx格式");
        return false;
      }
      // 准备读取文件数据
      this.excelFileData = file
      this.$message.success("上传成功")
    },
    // // 文件上传成功处理
    // handleFileSuccess(response, file, fileList) {
    //   this.upload.open = false;
    //   this.upload.isUploading = false;
    //   this.$refs.upload.clearFiles();
    //   this.$alert(
    //     "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
    //       response.msg +
    //       "</div>",
    //     "导入结果",
    //     { dangerouslyUseHTMLString: true }
    //   );
    //   // this.getList();
    // },
    // 提交上传文件
    submitFileForm() {
      this.$refs["batchform"].validate(valid => {
      if(this.excelFileData){
        const fileReader = new FileReader(this.excelFileData);
        fileReader.onload = (ev) => {
          try {
            const data = ev.target.result;
            let workbook = XLSX.read(data, {
              type: "binary",
            });

            // 取第一张表
            const wsname = workbook.SheetNames[0];
            // 生成json表格内容
            let ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]);
            // 循环 ws 取得其中的数据 
            // 把 ws 打印出来 就可以看得很清楚了 之后就进行自己想要的操作就可以了
            // 没有一样的代码 没有一样的需求
            
            if(ws.length>0){
                var temporary = [];
                for (let i = 0; i < ws.length; i++) {
                  if(ws[i].设备名称){
                    let temp = {
                      belongUser:this.batchform.belongUser,
                      composeId:this.batchform.composeId,
                      containerTypeId:this.batchform.containerTypeId,
                      cpuId:ws[i].cpuid,
                      // departmentId:ws[i].部门,
                      imeiCode:ws[i].imeiCode,
                      name:ws[i].设备名称,
                      projectId:this.batchform.projectId,
                      snCode:ws[i].snCode,
                      soleType:this.batchform.soleType,
                      // deviceId : (ws[i].唯一标识类型 == '1' ? ws[i].cpuId : (ws[i].唯一标识类型 == '2' ? ws[i].imeiCode : ws[i].snCode)),
                      // productId : 'master_thermostat',
                      // productName : '4G温控器&主控',
                    }
                    temporary.push(temp)
                  }
                  if(temporary[i].soleType == 1){
                    temporary[i].deviceId = temporary[i].cpuId
                  }else if(temporary[i].soleType == 2){
                    temporary[i].deviceId = temporary[i].imeiCode
                  }else{
                    temporary[i].deviceId = temporary[i].snCode
                  }
                }
                if(temporary.length === 0){
                  this.$message.warning("未读取合法数据，请检查excel")
                  return
                }
                this.$notify({
                  title: '提示',
                  message: '批量注册中,请稍后…',
                  offset: 700,
                  duration: 0
                });
                batchInsert(temporary)
                .then((res) => {
                  if(res.code === 200){
                    this.$message.success("注册成功,详情："+res.msg)
                    this.batchOpen = false
                    this.getMainDeviceList()
                  }else{
                    this.$message.warning("注册失败，原因："+res.msg)
                  }
                  this.$notify.closeAll();//去掉交互框
                  this.reset()
                })
                .catch((err) => {
                  this.$message.error('错误：'+err.message);
                }).finally(()=>{
                  this.$notify.closeAll();//去掉交互框
                  this.batchOpen = false
                  this.getMainDeviceList();
                  this.reset()
                  this.$refs.upload.clearFiles()
                })
             
            }else{
                this.$message({
                  type: "info",
                  message: "获取的列表为空，请检查表格是否有数据!",
                });
            }

          } catch (e) {
            return false;
          }
        };
        // 如果为原生 input 则应是 files[0]
        fileReader.readAsBinaryString(this.excelFileData.raw);
      }else{
        this.$message({
          type: 'warning',
          message: '请先上传Excel'
        })
      }
              
    })
    },
    /** 获取部门（品牌方）列表 */
    getDeptList() {
      listDept().then((res) => {
        if (res.code === 200 && res.data) {
          this.department_list = this.handleTree(res.data, "deptId");
        }
      })
    },
    /** 选择唯一标识类型 */
    chooseSoleType() {
      if (this.form.soleType == '1') {
        this.rules.cpuId[0].required = true
        this.rules.imeiCode[0].required = false
        this.rules.snCode[0].required = false
      } else if (this.form.soleType == '2') {
        this.rules.cpuId[0].required = false
        this.rules.imeiCode[0].required = true
        this.rules.snCode[0].required = false
      } else if (this.form.soleType == '3') {
        this.rules.cpuId[0].required = false
        this.rules.imeiCode[0].required = false
        this.rules.snCode[0].required = true
      } else {
        this.rules.cpuId[0].required = false
        this.rules.imeiCode[0].required = false
        this.rules.snCode[0].required = false
      }
    },
    /** 选择项目-获取冰柜类型和型号组合列表 */
    chooseProject() {
      // 清空
      this.form.composeId = ''
      this.form.containerTypeId = ''
      this.project_container_type_list_chose = []
      this.project_model_compose_list_chose = []
      // 重新获取
      var projectId = this.form.projectId;
      if(this.batchOpen == true){
        projectId = this.batchform.projectId
      }
      if (projectId) {
        getProjectDetail(projectId).then((res) => {
          if (res.code === 200 && res.data) {
            // 项目名下的 冰柜类型和型号组合
            if (res.data.modelGroup) {
              let projectModelCompose = [];
              if(res.data.modelGroup.indexOf(',') == -1){
                projectModelCompose.push(res.data.modelGroup)
              }else{
                projectModelCompose = res.data.modelGroup.split(',');
                projectModelCompose = projectModelCompose.filter(item => item);
              }           
              // 匹配型号组合
              this.project_model_compose_list_chose = projectModelCompose.map((pItem) => {
                const match = this.project_model_compose_list.find((item) => pItem == item.value)
                return match
              })
            }
            if (res.data.containerType) {
              let projectContainerType = [];
              if(res.data.containerType.indexOf(',') == -1){
                projectContainerType.push(res.data.containerType)
              }else{
                projectContainerType = res.data.containerType.split(',');
                projectContainerType = projectContainerType.filter(item => item);
              }    
              // 匹配冰柜类型
              this.project_container_type_list_chose = projectContainerType.map((pItem) => {
                const match = this.project_container_type_list.find((item) => pItem == item.value)
                return match
              })
            }
          }
        })
      }
    },

    /** 获取型号组合列表 */
    getDeviceModelComposeList() {
      listDeviceModelCompose().then((res) => {
        if (res.code === 200 && res.rows) {
          for (var i = 0; i < res.rows.length; i++) {
            let temp = {
              value: res.rows[i].id,
              label: res.rows[i].name
            }
            this.project_model_compose_list.push(temp)            
          }
        }
      }).catch((err) => {
        this.$message.error("型号组合列表获取失败，原因：" + err.message)
      }).finally(() => {
      })
    },
    /** 获取柜子类型列表 */
    getContainerTypeList() {
      listContainerType().then((res) => {
        if (res.code === 200 && res.rows) {
          for (var i = 0; i < res.rows.length; i++) {
            let temp = {
              value: res.rows[i].id,
              label: res.rows[i].name
            }
            this.project_container_type_list.push(temp)
          }
        }
      }).catch((err) => {
        this.$message.error("柜子类型列表获取失败，原因：" + err.message)
      }).finally(() => {
      })
    },
    /** 获取项目列表 */
    getProjectList() {
      listProject(this.queryParams).then((res) => {
        if (res.code === 200 && res.rows) {
          for (var i = 0; i < res.rows.length; i++) {
            let temp = {
              label: res.rows[i].projectName,
              value: res.rows[i].id
            }
            this.project_list.push(temp)
          }
        }
      }).catch((err) => {
        this.$message.error("项目列表获取失败，原因：" + err.message)
      })
    },
    /** 获取主设备列表 */
    getMainDeviceList() {
      const params = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        projectId:this.queryParams.projectId || this.$route.query.projectId,
        deviceId: this.queryParams.deviceId,
        name: this.queryParams.name,
        remark: this.queryParams.remark,
        orderByColumn:'id',
        isAsc:'desc'
      }
      if(this.$route.query.projectId){
        params.projectId = this.$route.query.projectId
      }
      this.loading = true;
      listMainDevice(params).then((res) => {
        if (res.code === 200) {
          this.mainDevicelList = res.rows
          this.total = res.total
        }
      }).catch((err) => {
        this.$message.error("设备列表获取失败，原因：" + err.message)
      }).finally(() => {
        this.$router.push({query:{}})
        this.loading = false;
        this.initSocket();
      })
    },
    // 取消按钮
    cancel() {
      if(this.batchOpen == true){
        this.$refs.upload.clearFiles()
      }
      
      this.open = false;
      this.batchOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      
      // this.form = {}
      this.excelFileData = ''
      this.form = {
        imeiCode: '',
        cpuId: '',
        snCode: ''
      },
      this.batchform = {
        projectId: '',
        containerTypeId: '',
        composeId: '',
        soleType: '',
        departmentId:'',
        belongUser:'',
      }
      this.userId = ''
      this.user_list = []
      this.project_container_type_list_chose = []
      this.project_model_compose_list_chose = []
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getMainDeviceList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.names = selection.map(item => item.name)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加主设备";
    },
    /**批量新增按钮操作 */
    handleBatch(){
      this.reset();
      this.batchOpen = true;
      this.batchTitle = "批量新增主设备";
      // this.exportList.push({
      //   belongUser: '',
      //   projectId: '',
      //   containerType: '',
      //   modelCompose: '',
      //   imeiCode: '',
      //   cpuId: '',
      //   snCode: '',
      //   belongUser: '',
      //   remark: ''
      // })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // 初始化
      this.reset();
      this.getContainerTypeList();
      this.getDeviceModelComposeList();
      const id = row.id || this.ids
      getMainDeviceDetail(id).then(response => {
        this.userId = response.data.belongUser;
        this.form = response.data;
        this.$forceUpdate()
        this.open = true;
        this.title = "修改主设备信息";
        getProjectDetail(this.form.projectId).then((res) => {
          if (res.code === 200 && res.data) {
            // 项目名下的 冰柜类型和型号组合
            if (res.data.modelGroup) {
              let projectModelCompose = [];
              if(res.data.modelGroup.indexOf(',') == -1){
                projectModelCompose.push(res.data.modelGroup)
              }else{
                projectModelCompose = res.data.modelGroup.split(',');
                projectModelCompose = projectModelCompose.filter(item => item);
              }           
              // 匹配型号组合
              this.project_model_compose_list_chose = projectModelCompose.map((pItem) => {
                const match = this.project_model_compose_list.find((item) => pItem == item.value)
                return match
              })
            }
            if (res.data.containerType) {
              let projectContainerType = [];
              if(res.data.containerType.indexOf(',') == -1){
                projectContainerType.push(res.data.containerType)
              }else{
                projectContainerType = res.data.containerType.split(',');
                projectContainerType = projectContainerType.filter(item => item);
              }    
              // 匹配冰柜类型
              this.project_container_type_list_chose = projectContainerType.map((pItem) => {
                const match = this.project_container_type_list.find((item) => pItem == item.value)
                return match
              })
            }

          }
        })
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            this.form.deviceId = (this.form.soleType == '1' ? this.form.cpuId : (this.form.soleType == '2' ? this.form.imeiCode : this.form.snCode))
            updateMainDevice(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getMainDeviceList();
            });
          } else {
            this.form.deviceId = (this.form.soleType == '1' ? this.form.cpuId : (this.form.soleType == '2' ? this.form.imeiCode : this.form.snCode))
            // this.form.productId = 'master_thermostat'
            // this.form.productName = '4G温控器&主控'
            addMainDevice(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getMainDeviceList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      //todos 修改
      const ids = row.id || this.ids;
      const names = row.name || this.names
      this.$modal.confirm('是否确认删除设备名称名为"' + names + '"的数据项？').then(function () {
        // 修改为逻辑删除
        return delMainDevice(ids);
      }).then(() => {
        this.getMainDeviceList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('/genius/platform-device/export', {
        ...this.queryParams
      }, `mainDevicelList_${new Date().getTime()}.xlsx`)
    },
    toSls(row){
      this.$router.push({
        path: '/system/log/slslog',
        query: {
          deviceId: row.deviceId
        }
      })
    }
  }
};
</script>
<style lang="scss">
.formTitle {
  width: 100%;
  text-align: center;
  margin: 15px 0 15px 0;
  font-weight: border;
  font-size: 20px
}

.status-icon {
  width: 10px;
  height: 10px;
  display: inline-block;
  border-radius: 50%;
}

.c-grey {
  background: grey;
}

.c-green {
  background: green;
}

.c-red {
  background: red;
}

.c-yellow {
  background: yellow;
}

.item-link {
  cursor: pointer;
  color: #409eff;
}

.one-line {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
</style>
